package net.ecpt.hrm.services;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.ExcelPoiUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

public class HrEmployeeSalaryXlsServices {
    public static final String module = HrEmployeeSalaryXlsServices.class.getName();

    /**
     * 导入
     */
    public static Map<String, Object> importXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
//	Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
	Delegator delegator = dctx.getDelegator();
	// List<GenericValue> toBeStore = new ArrayList();
	List<String> messageList = new ArrayList<String>();
	List<Map<String, Object>> sheetList = (List<Map<String, Object>>) context.get("sheetList");
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	// String createBy = userLogin.getString("partyId");
	try {
	    // Map<String, Object> row0 =sheetList.get(0);
	    // String salaryCode1_dicText = ExcelPoiUtils.getCellString(row0, 2);
	    int i = 0;

	    for (Map<String, Object> row : sheetList) {
		i = i + 1;
		// String id = ExcelPoiUtils.getCellString(row, 0);
		String partyId_dicText = ExcelPoiUtils.getCellString(row, 1);
		// 编号,员工姓名,基本工资 奖金 午餐补助 交通补助 加班费 绩效工资
		// 判断
		if (UtilValidate.isEmpty(partyId_dicText)) {
		    messageList.add("第" + (i + 1) + "行,员工姓名不能为空。");
		    continue;
		}

		List<GenericValue> personInfo = delegator.findByAnd("Person", UtilMisc.toMap("name", partyId_dicText),
			null, false);
		GenericValue person = EntityUtil.getFirst(personInfo);
		String partyId = person.getString("partyId");

		String amount2 = ExcelPoiUtils.getCellString(row, 2);
		if (UtilValidate.isNotEmpty(amount2)) {
		    saveHrSalary(delegator, partyId, "baseSalary", amount2);
		}
		String amount3 = ExcelPoiUtils.getCellString(row, 3);
		if (UtilValidate.isNotEmpty(amount3)) {
		    saveHrSalary(delegator, partyId, "rewardSalary", amount3);
		}
		String amount4 = ExcelPoiUtils.getCellString(row, 4);
		if (UtilValidate.isNotEmpty(amount4)) {
		    saveHrSalary(delegator, partyId, "dinnerAllowance", amount4);
		}
		String amount5 = ExcelPoiUtils.getCellString(row, 5);
		if (UtilValidate.isNotEmpty(amount5)) {
		    saveHrSalary(delegator, partyId, "travelAllowance", amount5);
		}
		String amount6 = ExcelPoiUtils.getCellString(row, 6);
		if (UtilValidate.isNotEmpty(amount6)) {
		    saveHrSalary(delegator, partyId, "overtimePay", amount6);
		}
		String amount7 = ExcelPoiUtils.getCellString(row, 7);
		if (UtilValidate.isNotEmpty(amount7)) {
		    saveHrSalary(delegator, partyId, "resultsWages", amount7);
		}
		dispatcher.runSync("saveHrSalaryAmount", UtilMisc.toMap("partyId", partyId,"userLogin",userLogin));
		
	    }
	    result.put("messageList", messageList);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	} catch (GenericServiceException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    private static GenericValue saveHrSalary(Delegator delegator, String partyId, String salaryCode, String amount)
	    throws GenericEntityException {
	Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
	// 增加是否过期查询条件 statusId=10
	List<GenericValue> hrSalary1List = delegator.findByAnd("HrSalary",
		UtilMisc.toMap("partyId", partyId, "statusId", "10", "salaryTypeId", salaryCode), null, false);
	GenericValue hrSalary1 = EntityUtil.getFirst(hrSalary1List);

	GenericValue entity = null;
	if (UtilValidate.isNotEmpty(hrSalary1)) {
	    entity = delegator.findOne("HrSalary", UtilMisc.toMap("id", hrSalary1.getString("id")), false);
	} else {
	    String id = delegator.getNextSeqId("HrSalary");
	    entity = delegator.makeValue("HrSalary", UtilMisc.toMap("id", id));
	    entity.set("statusId", "10");
	}

	entity.set("partyId", partyId);
	entity.set("salaryTypeId", salaryCode);

	entity.set("amount", new BigDecimal(amount));
	entity.set("description", "初始化");
	entity.set("fromDate", nowTimestamp);

	delegator.createOrStore(entity);
	return entity;
    }

    /**
     * 导出
     */

    public static Map<String, Object> exportXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	String ids = (String) context.get("ids");
	List<String> baseIdList = FastList.newInstance();
	if (UtilValidate.isNotEmpty(ids)) {
	    baseIdList = Arrays.asList(ids.split(";"));
	}
	Map<String, Object> result = ServiceUtil.returnSuccess();

	EntityCondition mainCond = null;
	List<EntityCondition> andExprs = FastList.newInstance();
	// andExprs.add(EntityCondition.makeCondition("parentProductId",
	// EntityOperator.EQUALS, "_NA_"));
	if (UtilValidate.isNotEmpty(baseIdList))
	    andExprs.add(EntityCondition.makeCondition("partyId", EntityOperator.IN, baseIdList));
	if (andExprs.size() > 0)
	    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	try {
	    List<GenericValue> entityList = delegator.findList("Person", mainCond, null, null, null, true);

	    List<Map<String, Object>> list = FastList.newInstance();
	    Map<String, Object> keyMap = FastMap.newInstance();
	    keyMap.put("0", "id");
	    keyMap.put("1", "partyId_dicText");
	    keyMap.put("2", "amount1");
	    keyMap.put("3", "amount2");
	    keyMap.put("4", "amount3");
	    keyMap.put("5", "amount4");
	    keyMap.put("6", "amount5");
	    keyMap.put("7", "amount6");
	    String headers = "编号,员工姓名,基本工资,奖金,午餐补助	,交通补助,加班费,绩效工资";
	    result.put("headers", headers);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		String partyId = entity.getString("partyId");

		GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), false);
		String partyId_dicText = person.getString("name");

		map.put("id", partyId);
		map.put("partyId_dicText", partyId_dicText);
		map.put("amount1", 0);
		map.put("amount2", 0);
		map.put("amount3", 0);
		map.put("amount4", 0);
		map.put("amount5", 0);
		map.put("amount6", 0);
		List<GenericValue> hrSalaryList = delegator.findByAnd("HrSalary",
			UtilMisc.toMap("partyId", partyId, "statusId", "10"), null, false);

		for (GenericValue hrSalary : hrSalaryList) {

		    String salaryTypeId = hrSalary.getString("salaryTypeId");
		    String amount = hrSalary.getString("amount");
		    if ("baseSalary".equals(salaryTypeId)) {
			map.put("amount1", amount);
		    }
		    if ("rewardSalary".equals(salaryTypeId)) {
			map.put("amount2", amount);
		    }
		    if ("dinnerAllowance".equals(salaryTypeId)) {
			map.put("amount3", amount);
		    }
		    if ("travelAllowance".equals(salaryTypeId)) {
			map.put("amount4", amount);
		    }
		    if ("overtimePay".equals(salaryTypeId)) {
			map.put("amount5", amount);
		    }
		    if ("resultsWages".equals(salaryTypeId)) {
			map.put("amount6", amount);
		    }

		}

		list.add(map);
	    }
	    result.put("list", list);
	    result.put("keyMap", keyMap);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

}
